import Mn from 'backbone.marionette';

import {
    displayServerSuccess,
    displayServerError
} from 'backbone-tools.js';
import ErrorView from 'base/views/ErrorView.js';

import TaskGroupModel from 'task/models/TaskGroupModel.js';
import TaskGroupCollectionView from './TaskGroupCollectionView.js';
import TaskGroupFormView from './TaskGroupFormView.js';
import {
    strToFloat
} from 'math.js';


const LinesComponent = Mn.View.extend({
    /*
     * wrapper for TaskGroup and TaskLine collections
     * It takes the following parameters

        collection

           TaskLineGroups

        edit

            Can we edit groups and lines

        section

            The form section configuration

     *
     */

    template: require('./templates/LinesComponent.mustache'),
    tagName: 'div',
    className: 'form-section',
    regions: {
        errors: '.group-errors',
        container: '.group-container',
        modalRegion: ".group-modalregion",
    },
    ui: {
        add_button: 'button.add',
    },
    triggers: {
        "click @ui.add_button": "group:add"
    },
    childViewEvents: {
        'group:edit': 'onGroupEdit',
        'group:delete': 'onGroupDelete',
        'catalog:insert': 'onCatalogInsert',
    },
    collectionEvents: {
        'change': 'hideErrors'
    },
    initialize: function (options) {
        this.collection = options['collection'];
        this.listenTo(this.collection, 'validated:invalid', this.showErrors);
        this.listenTo(this.collection, 'validated:valid', this.hideErrors.bind(this));
        this.edit = options['edit'];
        this.section = options['section'];
    },
    showErrors(model, errors) {
        this.detachChildView('errors');
        this.showChildView('errors', new ErrorView({
            errors: errors
        }));
        this.$el.addClass('error');
    },
    hideErrors(model) {
        this.detachChildView('errors');
        this.$el.removeClass('error');
    },
    onDeleteSuccess: function () {
        displayServerSuccess("Vos données ont bien été supprimées");
    },
    onDeleteError: function () {
        displayServerError("Une erreur a été rencontrée lors de la " +
            "suppression de cet élément");
    },
    onGroupDelete: function (childView) {
        var result = window.confirm("Êtes-vous sûr de vouloir supprimer ce chapitre ?");
        if (result) {
            childView.model.destroy({
                success: this.onDeleteSuccess,
                error: this.onDeleteError
            });
        }
    },
    onGroupEdit: function (childView) {
        this.showTaskGroupForm(childView.model, "Modifier ce chapitre", true);
    },
    onGroupAdd: function () {
        var model = new TaskGroupModel({
            order: this.collection.getMaxOrder() + 1
        });
        this.showTaskGroupForm(model, "Ajouter un chapitre", false);
    },
    showTaskGroupForm: function (model, title, edit) {
        const form = new TaskGroupFormView({
            model: model,
            title: title,
            destCollection: this.collection,
            section: this.section,
            edit: edit
        });

        this.showChildView('modalRegion', form);
    },
    onCatalogInsert: function (sale_products) {
        this.collection.load_from_catalog(sale_products);
        this.getChildView('modalRegion').triggerMethod('modal:close')
    },
    onChildviewDestroyModal: function () {
        this.detachChildView('modalRegion');
        this.getRegion('modalRegion').empty();
    },
    onRender: function () {
        const view = new TaskGroupCollectionView({
            collection: this.collection,
            edit: this.edit,
            section: this.section
        })

        this.showChildView('container', view);
    },
    templateContext() {
        return {
            can_add: this.section['can_add'] && this.edit
        };
    }
});
export default LinesComponent;